<?php
/**
 * Created by PhpStorm.
 * User: Keter
 * Date: 2016/8/3
 * Time: 16:55
 */
class OnlineLogQueen extends StatsLogBase
{
    public $queenName = 'onlineLog';
    public $baseTableName = 'online_log';
    public $dbName = 'online_log';

    /**
     * 推入队列
     * @param $data
     * @return bool
     * @throws Exception
     */
    public function push($data)
    {
        return parent::pushQueen($data,'push_online_log_error', 'user_stats');
    }

    /**
     * 保存到数据库
     * @param $data
     * @return array
     */
    public function saveLog($data)
    {
        /**
         * 检测分库
         */
        $result = $this->checkDatabase($data['createTime']);
        if (!$result) {
            $this->e('cannot_select_database');
            return false;
        }

        /**
         * 检查表是否存在
         */
        if (!$this->checkTableExists()) {
            return [];
        }

        /**
         * 保存日志数据
         */
        $result = $this->mysql->findRow($this->tableName, ['uid' => $data['uid'], 'timePoint' => $data['timePoint']], '1', true);

        if (empty($result)) {
            if ($this->mysql->error()) {
                $this->e('query_error', $this->mysql->error());
                $this->e('用户在线日志查询失败', $data);
                return [];
            }
            $result = $this->mysql->insert($this->tableName, $data, true);
            if (!$result) {
                $this->e('save_error', $this->mysql->error());
                $this->e('用户在线日志保存失败', $data);
                return [];
            }
        }

        return $data;
    }

    /**
     *
     * @param $tableName
     * @return string
     */
    public function getCreateTableSql($tableName)
    {
        $sql = "CREATE TABLE `{$tableName}` (
            `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
            `uid` int(11) unsigned NOT NULL,
            `timePoint` smallint(4) unsigned NOT NULL DEFAULT 0,
            `roomID` int(11) unsigned NOT NULL DEFAULT 0,
            `majiangType` int(11) unsigned NOT NULL DEFAULT 0,
            `platform` tinyint(1) NOT NULL DEFAULT 0,
            `channelID` int(11) NOT NULL DEFAULT 0,
            `ver` varchar(30) NOT NULL DEFAULT '',
            `paiZuID` varchar(50) NOT NULL,
            `seq` tinyint(3) unsigned NOT NULL DEFAULT 1,
            `createTime` int(11) NOT NULL DEFAULT 0,
            PRIMARY KEY (`id`),
            KEY `uid` (`uid`),
            KEY `timePoint` (`timePoint`)
            ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='用户在线日志表'";

        return $sql;
    }
}